<template>
  <ElCard>
    <div class="flex justify-start mb-5">
      <el-button class="mr-2" type="primary" @click="returnPage">返回</el-button>
      <el-button class="mr-2" type="primary" :disabled="pageState == 2" @click="saveProductionPlan(0)">{{ pageState == 1 ? '更新' : '保存'}}</el-button>
      <el-button class="mr-2" type="primary" :disabled="pageState == 2" @click="saveProductionPlan(1)">{{ pageState == 1 ? '更新并生效' : '保存并生效'}}</el-button>
    </div>
    <div class="production-scheduling">
      <el-form class="flex flex-wrap justify-start" style="align-items: center;" :disabled="pageState != 0" label-width="120px">
        <el-form-item label="排产周期:">
          <el-select v-model="schedulingType" style="width: 200px" placeholder="请选择" @change="changeSchedulingType">
            <el-option v-for="item in schedulingTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="月份:" v-if="schedulingType === 'month'">
          <el-date-picker v-model="formData.planMonth" type="month" placeholder="选择月份" format="YYYY-MM" value-format="YYYY-MM" @change="changeMonth" style="width:200px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="计划日期:" v-if="schedulingType === 'day'">
          <el-date-picker style="width:200px" v-model="formData.planDate" type="date" placeholder="选择计划日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="planDayChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="计划起始日期:" v-if="schedulingType === 'dateRange'">
          <el-date-picker style="width:200px" v-model="formData.planRangeDate" type="daterange" :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="planDayRangeChange"></el-date-picker>
        </el-form-item>
        <el-form-item label="生产订单">
          <el-input :value="formData.productOrder" placeholder="请选择生产订单" style="width: 200px">
             <template #append>
              <el-button :icon="Search" @click="openOrderDialog"/>
             </template>
          </el-input>
        </el-form-item>
        <el-form-item label="车间">
          <el-input :value="formData.gridName" disabled style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="产线">
          <el-select v-model="formData.lineCodes" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="1" @focus="lineCodesFocus" @change="lineCodesChange" placeholder="请选择产线" style="width:200px;">
            <el-option v-for="line in formData.lineList" :label="line.name" :value="line.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料">
          <el-input :value="formData.materialName" disabled style="width:200px;"></el-input>
        </el-form-item>
        <el-form-item label="计划排产数量">
          <el-input :value="formData.schedulingQuantity" disabled style="width:200px;"/>
        </el-form-item>
        <el-form-item label="工艺">
          <el-select v-model="formData.craftId" placeholder="请选择工艺" @change="craftChangeEvent" style="width:200px;">
            <el-option v-for="craft in formData.craftList" :label="craft.craftName" :value="craft.craftId"></el-option>
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="工序">
          <el-select v-model="formData.processIds" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="1" placeholder="请选择工序" style="width:200px;">
            <el-option v-for="process in formData.processList" :label="process.procedureName" :value="process.procedureId"></el-option>
          </el-select>
        </el-form-item>
        -->
        <el-form-item label="备注:">
          <el-input v-model="formData.remark" :rows="1" type="textarea" style="width:200px;"/>
        </el-form-item>
      </el-form>

      <!-- card-工序选择 -->
      <el-card style="width:100%;margin-bottom:10px;max-height: 120px;">
        <template #header>
          <div class="card-header">
            <span>选择工序</span>
          </div>
        </template>
        <div v-if="formData.processList.length" style="max-height: 80px;overflow: auto;">
          <el-checkbox-group v-model="formData.processIds" :disabled="pageState != 0">
            <el-checkbox v-for="process in formData.processList" :label="process.procedureName" :value="process.procedureId"/>
          </el-checkbox-group>
        </div>
        <div v-else style="font-size: 12px;color:#9195a3;">请先在上方选择工艺</div>
      </el-card>

      <!-- 表格-排产明细表 -->
      <el-card style="width:100%">
        <template #header>
          <div class="card-header">
            <span>排产明细表</span>
          </div>
        </template>
        <el-table :data="materialList" border style="width: 100%; margin-top: 20px">
          <el-table-column prop="lineName" label="产线" align="center" width="200"></el-table-column>
          <el-table-column prop="schedulingQuantity" label="排产数量" align="center" width="200">
            <template #default="scope">
              {{ scope.row.schedulingQuantity }}
            </template>
          </el-table-column>
          <!-- 动态生成日期列 -->
          <el-table-column v-for="(dateString, index) in formattedDateColumns" :key="index" :prop="dateString" :label="dateString" :width="dealTableWidth()" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.scheduleQuantities[dateString]" :min="0" @change="inputScheduling(scope.row,index)" :disabled="pageState == 2" style="width:130px" placeholder="" class="quantity-input"></el-input-number>
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <!-- <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <Button type="link" style="color:red;" @click="deleteRow(scope.$index)">删除</Button>
            </template>
          </el-table-column> -->
        </el-table>
      </el-card>

      <!-- 选择生产订单弹窗 -->
      <el-dialog v-model="orderDialogVisible" title="选择生产订单" @close="dialogCancel_btn" :close-on-click-modal="false" width="80%">
        <el-table :data="orderList" v-loading="loadingDialog" ref="dialogTableRef" @select="handleSelectionChange" @selectAll="dialogTableRef.clearSelection();" max-height="500">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="saleOrderCode" label="销售订单号"></el-table-column>
          <el-table-column prop="gridName" label="车间"></el-table-column>
          <el-table-column prop="productionOrderNumber" label="生产订单号">
            <template #header>
              <table-header-filter label="生产订单号" :bind-data="dialogFormData.productionOrderNumber" type="input" filterField="productionOrderNumber" @change="filterChangeEvent"></table-header-filter>
            </template>
          </el-table-column>
          <el-table-column prop="instructionNumber" label="制令号"></el-table-column>
          <el-table-column prop="materialCode" label="物料编码">
            <template #header>
              <table-header-filter label="物料编码" :bind-data="dialogFormData.materialCode" type="input" filterField="materialCode" @change="filterChangeEvent"></table-header-filter>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称">
            <template #header>
              <table-header-filter label="物料名称" :bind-data="dialogFormData.materialName" type="input" filterField="materialName" @change="filterChangeEvent"></table-header-filter>
            </template>
          </el-table-column>
          <el-table-column prop="materialType" label="物料类型"></el-table-column>
          <el-table-column prop="materialComp" label="物料单位"></el-table-column>
          <el-table-column prop="orderQuantity" label="计划数量"></el-table-column>
          <el-table-column prop="businessMan" label="销售员"></el-table-column>
        </el-table>
        <div class="block" style="display: flex; justify-content: flex-end">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50, 100]" :total="total" layout="total, sizes, prev, pager, next" @size-change="sizeChangeEvent" @current-change="currentChangeEvent"></el-pagination>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="orderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="productOrderDialogConfirm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </ElCard>
</template>

<script setup>
import { onMounted,ref,unref,reactive } from "vue";
import { ElButton,ElCard,ElDatePicker,ElDialog,ElForm,ElSelect,ElFormItem,ElTable,ElTableColumn,ElInput,ElInputNumber,ElLoading,ElMessage,ElPagination,ElRadio,ElRadioGroup,ElRadioButton,ElOption,ElNotification,ElCheckboxGroup,ElCheckbox } from "element-plus";
import { Plus,Search } from '@element-plus/icons-vue';
import { Button } from "ant-design-vue";
import { getSaleOrderApi, saveProductionPlanApi, getStockApi,listMaterialsApi} from "#/api/productionPlan/index.js";
import { reqProductOrders,reqLineListByGrid,reqCraftListByGrid,reqSaveLineScheduling,reqLineSchedulingById,reqUpdateLineScheduling } from "#/api/productionPlan/index.js";
import { useRoute, useRouter } from "vue-router";
import TableHeaderFilter from "#/components/tableHeardFilter.vue";
import { lodash,sleep,dayjs,getRandom } from "#/utils/tools";
const router = useRouter(),route = useRoute();
const { id,state } = route.query;
const pageState = ref(0);  //0-添加 1-修改 2-查看

// 排产类型（周/月）
const schedulingType = ref("day");
const schedulingTypeOptions = [
  {value: "day",label: "日"},
  {value: "month",label: "月"},
  {value:"dateRange",label:"日期区间"}
];
const month = ref(null);

const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 物料列表
const materialList = ref([]);
const formData = reactive({
  type: 0,
  planDate: dayjs().format("YYYY-MM-DD"),
  planRangeDate:[],
  planMonth:"",
  productOrder:"",
  gridName:"",
  lineList:[],
  lineCodes:[],
  materialName:"",
  schedulingQuantity:"",
  craftList:[],
  craftId:"",
  processList:[],
  processIds:[],
  remark:"",
  id:""
});
const loadingDialog = ref(true);

// 生产订单列表
const orderList = ref([]);
const dialogFormData = ref({});

const gridList = ref([]);

const orderDialogVisible = ref(false);

// 日期列（动态生成）
const dateColumns = ref([]);
const formattedDateColumns = ref([]); // 格式化后的日期列

const dialogTableRef = ref(null);
let selectedOrderTmp = null;
let selectedOrder = null;

// 返回事件
const returnPage = () => {
  router.push({ name: "OmSchedulingList" }); // 返回列表页
};

// 表格计算排产数量
const inputScheduling = (row, index) => {
  row.schedulingQuantity = Object.values(row.scheduleQuantities).reduce((sum, current) => sum + current,0);
  console.log("行数据====>", row);
}

// 切换排产周期
const changeSchedulingType = () => {
  if(schedulingType.value === "month"){
    formData.planMonth = dayjs().format("YYYY-MM");
    formattedDateColumns.value.splice(0, dateColumns.value.length);
  }
  if(schedulingType.value === "dateRange"){
    const s = dayjs().format("YYYY-MM-DD");
    const e = dayjs().add(7, "day").format("YYYY-MM-DD");
    formData.planRangeDate = [s,e];
    formattedDateColumns.value.splice(0, dateColumns.value.length);
  }
  generateDateColumns();
};
// 切换月份
const changeMonth = () => {
  generateDateColumns();
};
//切换日期
const planDayChange = () => {
  console.log("计划日期", formData.planDate);
  generateDateColumns();
}
//切换日期区间
const planDayRangeChange = () => {
  const [startDate, endDate] = formData.planRangeDate;
  const timeDiff = Math.abs(new Date(endDate).getTime() - new Date(startDate).getTime());
  const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
  if(dayDiff > 30){
    formData.planRangeDate = [];
    return ElMessage.info("日期区间不能超过30天");
  }
  generateDateColumns();
}

// 生成日期列
const generateDateColumns = () => {
  const { planDate,planMonth,planRangeDate } = formData;
  const columns = [];

  // 设置日期为当前日期加上指定的天数
  // today.setDate(today.getDate() + 30);
  if (schedulingType.value === "dateRange") {
    if(planRangeDate.length !== 2) return;
    const [startDate, endDate] = planRangeDate;
    const timeDiff = Math.abs(new Date(endDate).getTime() - new Date(startDate).getTime());
    const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
    const start = new Date(startDate);
    for (let d = 0; d < dayDiff; d++) {
      columns.push(new Date(start));
      start.setDate(start.getDate() + 1);
    }
  } else if (schedulingType.value === "month") {
    const date = new Date(planMonth);
    const currentYear = date.getFullYear();
    const currentMonth = date.getMonth();
    console.log("月份2", currentYear, currentMonth);
    // 创建一个表示下个月第一天的日期对象
    const nextMonthStart = new Date(currentYear, currentMonth, 1);
    // 创建一个表示下下个月第一天的日期对象（用于获取下个月的最后一天）
    const nextMonthEnd = new Date(currentYear, currentMonth, 0);
    // 获取下个月的天数
    const daysInNextMonth = nextMonthEnd.getDate();
    // 按月生成下个月每一天的日期
    for (let i = 1; i <= daysInNextMonth; i++) {
      const currentDate = new Date(currentYear, currentMonth, i);
      columns.push(currentDate);
    }
  } else {
    const curDay = new Date(planDate);
    columns.push(curDay);
  }
  dateColumns.value = columns;
  formattedDateColumns.value = columns.map((date) => formatDate(date)); // 格式化日期为字符串

  // 清空之前的数据
  materialList.value.forEach((material) => {
    material.scheduleQuantities = {};
    material.schedulingQuantity = 0;
  });
  formattedDateColumns.value.forEach((date) => {
    materialList.value.forEach((num) => {
      num.scheduleQuantities[date] = 0;
    });
  });
};

// 打开订单选择弹窗
const openOrderDialog = () => {
  orderDialogVisible.value = true;
  getProductOrderList();
};

//获取生产订单列表
function getProductOrderList() {
  loadingDialog.value = true;
  const params = Object.fromEntries(
    Object.entries(dialogFormData.value).filter(
      ([key, value]) => value !== "" && value !== null && value !== undefined
    )
  );
  console.log(params);
  reqProductOrders({ size: pageSize.value, page: currentPage.value, ...params })
    .then((response) => {
      orderList.value = response.data.content;
      total.value = response.data.totalElements;
      loadingDialog.value = false;
      console.log("获取生产订单列表!", response);
    })
    .catch((error) => {
      loadingDialog.value = false;
      console.log("获取销售订单列表失败!", error);
    });
}
//通过车间获取产线列表
const getLineListByGrid = () => {
  formData.lineList = [];
  formData.lineCodes = [];
  const {gridCode,gridName} = selectedOrder;
  const params = {
    gridCode:'1c1j8yh524' || gridCode
  };
  reqLineListByGrid(params).then((response) => {
    formData.lineList = response.data || [];
  },error => {
    ElNotification({title:'提示',message:`产线列表获取失败${error.data?.message}`,type:'error'});
  });
}

//通过车间获取工艺路线
const getCraftListByGrid = () => {
  return new Promise((resolve,reject) => {
    formData.craftList = [];
    formData.craftId = '';
    formData.processList = [];
    const {gridCode,gridName} = selectedOrder;
    const params = {
      gridCode:'1c1j8yh524' || gridCode
    };
    reqCraftListByGrid(params).then((response) => {
      const list = response.data || [];
      const craftMap = new Map();
      list.forEach(item => {
        if(!craftMap.has(item.craftId)){
          const processList = list.filter(val => val.craftId == item.craftId).map(v => {
            return {
              sequence:v.sequence,
              procedureId:v.procedureId,
              procedureName:v.procedureName,
              supProcedureName:v.supProcedureName,
              isLastProcedure:v.isLastProcedure,
              procedureCode:v.procedureCode
            }
          })
          craftMap.set(item.craftId,{ craftId:item.craftId,craftName:item.name,processList});
        }
      })
      formData.craftList = Array.from(craftMap.values());
      //formData.craftId = formData.craftList.length ? formData.craftList[0].craftId : '';
      //formData.processList = formData.craftList.length ? formData.craftList[0].processList : [];
      resolve();
    },error => {
      ElNotification({title:'提示',message:`工艺列表获取失败${error.data?.message}`,type:'error'});
      reject();
    });
  })
}

const craftChangeEvent = (craftId) => {
  formData.processList = [];
  formData.processIds = [];
  const craft = formData.craftList.find(val => val.craftId == craftId);
  if(craft) formData.processList = craft.processList;
}


function getMaterialList() {
  loadingDialog.value = true;
  const params = Object.fromEntries(
    Object.entries(dialogFormData2.value).filter(
      ([key, value]) => value !== "" && value !== null && value !== undefined
    )
  );
  // 使用 params 发起请求
  console.log("params", params); // 此时 params 中不包含值为空的字段
  listMaterialsApi({ size: pageSize.value, page: currentPage.value, ...params })
    .then((response) => {
      console.log("content", response.data.content);
      materialDialogList.value = response.data.content;
      total.value = response.data.totalElements;
      loadingDialog.value = false;
    })
    .catch((error) => {
      loadingDialog.value = false;
      console.error("获取物料列表失败!", error);
    });
}

function dialogCancel_btn() {
  orderDialogVisible.value = false;
  dialogFormData.value = {};
  currentPage.value = 1;
  pageSize.value = 10;
  total.value = 0;
}

function search_btn() {
  getProductOrderList();
}


function search_btn3() {
  getStockList();
}

function sizeChangeEvent(val) {
  pageSize.value = val;
  getProductOrderList();
}

function currentChangeEvent(val) {
  currentPage.value = val;
  getProductOrderList();
}
function sizeChangeEvent3(val) {
  pageSize.value = val;
  getStockList();
}

function currentChangeEvent3(val) {
  currentPage.value = val;
}

// 处理订单选择
const handleSelectionChange = (selection,row) => {
  dialogTableRef.value.clearSelection();
  dialogTableRef.value.toggleRowSelection(row, true);
  selectedOrderTmp = row;
};

const clearFormData = () => {
  formData.productOrder = '';
  formData.gridName = '';
  formData.materialName = '';
  formData.schedulingQuantity = '';
  formData.lineList = [];
  formData.lineCodes = [];
  formData.schedulingQuantity = '';
  formData.craftList = [];
  formData.craftId = '';
  formData.processIds = [];
  formData.processList = [];
  formData.remark = '';
  selectedOrder = null;
  materialList.value = [];
};

const productOrderDialogConfirm = () => {
  clearFormData();
  selectedOrder = selectedOrderTmp;
  const { productionOrderNumber,gridName,gridCode,materialCode,materialName,materialId,orderQuantity,instructionNumber } = selectedOrder;
  formData.productOrder = productionOrderNumber;
  formData.gridName = gridName;
  formData.materialName = materialName;
  formData.schedulingQuantity = orderQuantity;
  console.log("选择的生产订单===>",selectedOrder);
  orderDialogVisible.value = false;
  selectedOrderTmp = null;
  getLineListByGrid();
  getCraftListByGrid();
}


const dealScheduleQuantities = () => {
  const dateColumns = unref(formattedDateColumns);
  const scheduleQuantities = {};
  for(let i = 0; i < dateColumns.length; i++){
    scheduleQuantities[dateColumns[i]] = 0;
  }
  return scheduleQuantities;
}

//添加行数据
const addRowEvent = () => {
  const { lineCodes,lineList } = formData;
  //if(!validataFormData()) return;
  const { schedulingQuantity } = selectedOrder;
  const isSchedulingLineCodes = materialList.value.map(v => v.lineCode);
  const needSchedulingLineCodes = lineCodes.filter(code => !isSchedulingLineCodes.includes(code));
  for(let l = 0; l < needSchedulingLineCodes.length; l++){
    const lineInfo = lineList.find(v => v.code == needSchedulingLineCodes[l]);
    const newRow = {
      randomId:getRandom(),
      schedulingQuantity,
      scheduleQuantities:dealScheduleQuantities(),
      lineCode:lineInfo ? lineInfo.code : '',
      lineName:lineInfo ? lineInfo.name : ''
    };
    materialList.value.push(newRow);
  }
};
const deleteRowEvent = () => {
  const { lineCodes,lineList } = formData;
  const tableListLineCodes = unref(materialList).map(v => v.lineCode);
  const removedLines = tableListLineCodes.filter(code => !lineCodes.includes(code));
  for(let i = 0; i < removedLines.length; i ++){
    const index = unref(materialList).findIndex(val => val.lineCode == removedLines[i]);
    if(index !== -1) materialList.value.splice(index, 1);
  }
}
const lineCodesChange = () => {
  const { lineCodes,lineList } = formData;
  const tableListLineCodes = unref(materialList).map(v => v.lineCode);
  if(!lineCodes.length) materialList.value = [];
  const addedLines = lineCodes.filter(code => !tableListLineCodes.includes(code));
  const removedLines = tableListLineCodes.filter(code => !lineCodes.includes(code));
  if(addedLines.length){
    addRowEvent();
  }
  if(removedLines.length){
    deleteRowEvent();
  }
}
const lineCodesFocus = () => {
  const { lineCodes,lineList,productOrder } = formData;
  if(!lineList.length){
    ElNotification({title:'提示',message:"请先选择生产订单后再选择产线",type:'warning'});
  }
}

// 根据 materialCode 合并 orderQuantity 的函数
function mergeOrdersByMaterialCode(orders) {
  const merged = {};
  for (const order of orders) {
    const { materialCode, orderQuantity, materialName,saleOrderCode,productionOrderNumber,instructionNumber,materialComp,orderRequire,businessMan } = order;
    //** 如果 materialCode 已经存在，则累加 orderQuantity，否则初始化
    merged[materialCode] = {
      productionOrderNumber,
      orderQuantity: orderQuantity,
      materialCode,
      materialName,
      scheduleQuantities: {}, // 初始化 scheduleQuantities 对象
      saleOrderCode,
      instructionNumber,
      materialComp,
      orderRequire,
      businessMan
    };
  }
  return Object.values(merged);
}

// 格式化日期为字符串
const formatDate = (date) => {
  return date
    ? `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    : "";
};

// 格式化计划时间
const formatPlanTime = (dateString) => {
  const [year, month, day] = dateString.split("-");
  return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
};

const validataFormData = () => {
  const type = schedulingType.value;
  const order = selectedOrder;
  const { planDate,planMonth,planRangeDate,productOrder,gridName,lineCodes,materialName,schedulingQuantity,craftId,processIds } = formData;
  if(type == 'day' && !planDate){
    ElNotification({title:'提示',message:'请选择计划日期',type:'warning'});
    return false;
  }
  if(type == 'month' && !planMonth){
    ElNotification({title:'提示',message:'请选择月份',type:'warning'});
    return false;
  }
  if(type == 'dateRange' && planRangeDate.length !== 2){
    ElNotification({title:'提示',message:'请选择起始日期',type:'warning'});
    return false;
  }
  if(!order){
    ElNotification({title:'提示',message:'请先选择一个订单',type:'warning'});
    return false;
  }
  if(!lineCodes.length){
    ElNotification({title:'提示',message:'请至少选择一条产线',type:'warning'});
    return false;
  }
  if(!craftId){
    ElNotification({title:'提示',message:'请选择一个工艺',type:'warning'});
    return false;
  }
  if(!processIds.length){
    ElNotification({title:'提示',message:'请至少选择一个工序',type:'warning'});
    return false;
  }
  if (!materialList.value || materialList.value.length === 0) {
    ElNotification({title:'提示',message:"排产明细表为空",type:'warning'});
    return false;
  }
  return true;
};
// 组装接口参数
const assembleParams = (state) => {
  const { craftId,craftList,processIds,processList,remark,id } = formData;
  const selectedcraft = craftList.find(v => v.craftId == craftId);
  const selectedProcessList = processList.filter(v => processIds.includes(v.procedureId));
  const selectedOrderOriginal = lodash.cloneDeep(selectedOrder);
  const { productionOrderNumber,orderQuantity,materialId,materialCode,materialName,instructionNumber,gridCode,gridName } = selectedOrderOriginal;
  const tableList = unref(materialList);
  const lineSchedulingMaterialList = [];
  let totalSchedulingQuantity = 0;
  for(let k = 0; k < tableList.length; k ++){
    const {lineCode,lineName,schedulingQuantity,scheduleQuantities,id} = tableList[k];
    const lineSchedulingMaterialNumberList = [];
    for (const [dateString, quantity] of Object.entries(scheduleQuantities)) {
      if (quantity > 0) {
        lineSchedulingMaterialNumberList.push({
          schedulingTime: formatPlanTime(dateString),
          quantity:quantity
        });
      }
    }
    totalSchedulingQuantity =  totalSchedulingQuantity + schedulingQuantity;
    const obj = {
      id:id ? id : '',
      lineCode,
      lineName,
      schedulingQuantity,
      lineSchedulingMaterialNumberList
    }
    lineSchedulingMaterialList.push(obj);
  }
  const parameter = {
    id:id ? id : '',
    state,
    productOrderNumber:productionOrderNumber,
    materialId,
    materialCode,
    materialName,
    materialSpecification:"",
    planQuantity:orderQuantity,
    schedulingQuantity:totalSchedulingQuantity,
    instructionNumber,
    gridCode,
    gridName,
    craftId,
    craftName:selectedcraft ? selectedcraft.craftName : "",
    craftCode:"",
    procedureList:selectedProcessList,
    lineSchedulingMaterialList,
    remark
  }
  return parameter;
};
// 保存按钮的点击事件
const saveProductionPlan = (state = 0) => {
  if(!validataFormData()) return;
  let executeFunction = null;
  if(unref(pageState) == 0){
    executeFunction = reqSaveLineScheduling;
  }
  if(unref(pageState) == 1){
    executeFunction = reqUpdateLineScheduling;
  }
  const loading = ElLoading.service({lock: true,text: "加载中...",spinner: "el-icon-loading",background: "rgba(0, 0, 0, 0.7)",});
  const parameter = assembleParams(state);
  console.log("请求参数===>",parameter);
  return;
  executeFunction(parameter).then((response) => {
    ElNotification({title:'提示',message:`${unref(pageState) == 1 ? '更新成功' : '保存成功'}`,type:'success'});
    clearFormData();
  }).catch((error) => {
    ElNotification({title:'提示',message:`${unref(pageState) == 1 ? '更新失败,请重试' : '保存失败,请重试'}`,type:'error'});
  }).finally(() => {
    loading.close();
  });
};

const dealDateColumn = (schedulingList) => {
  const dateList = schedulingList[0]?.lineSchedulingMaterialNumberList.map( v => v.schedulingTime);
  if(dateList.length === 1){
    formData.schedulingType = 'day';
    formData.planDate = dateList[0];
  } else if(dateList.length > 1){
    formData.schedulingType = 'dateRange';
    const sortDateList = dateList.sort();
    const startDate = sortDateList[0],endDate = sortDateList[sortDateList.length - 1];
    formData.planDayChange = [startDate,endDate];
  }
  generateDateColumns();
}
//通过id获取产线排产数据
const getLineSchedulingById = async () => {
  const id = route.query.id;
  try {
    const response = await reqLineSchedulingById(id);
    const { productOrderNumber,state,materialId,materialCode,materialName,planQuantity,schedulingQuantity } = response.data;
    const { instructionNumber,gridCode,gridName,procedureList,lineSchedulingMaterialList,craftId,craftName,craftCode } = response.data;
    const lineCodes = [];
    selectedOrder = { gridCode,gridName,productionOrderNumber:productOrderNumber,orderQuantity:planQuantity,materialId,materialName,materialCode,instructionNumber };
    const tableList = [];
    dealDateColumn(lineSchedulingMaterialList);
    for(let o = 0; o < lineSchedulingMaterialList.length; o ++){
      const {id,lineCode,lineName,schedulingQuantity,lineSchedulingMaterialNumberList} = lineSchedulingMaterialList[o];
      lineCodes.push(lineCode);
      const scheduleQuantities = {};
      lineSchedulingMaterialNumberList.forEach(item => scheduleQuantities[item.schedulingTime] = Number(item.quantity));
      const obj = {id,schedulingQuantity,lineCode,lineName,scheduleQuantities};
      tableList.push(obj);
    }
    materialList.value = tableList;
    formData.id = id;
    formData.productOrder = productOrderNumber;
    formData.gridName = gridName;
    formData.materialName = materialName;
    formData.schedulingQuantity = planQuantity;
    getLineListByGrid();
    formData.lineCodes = lineCodes;
    await getCraftListByGrid();
    const craft = formData.craftList.find(val => val.craftId == craftId);
    if(craft) formData.processList = craft.processList;
    formData.processIds = procedureList.map(v => v.procedureId);
    formData.craftId = craftId;
  } catch (error) {
    console.log(error);
    ElNotification({title:'提示',message:`产线排产数据获取失败${error.response?.message}`,type:'warning'});
  }
}

onMounted(() => {
  if(state) pageState.value = state;
  generateDateColumns();
  if(id && unref(pageState) > 0){
    getLineSchedulingById();
  }
});

//dialogFormData筛选
const filterChangeEvent = (parameter) => {
  const { state, filterField, selectedValue } = parameter;
  //清空操作
  if (state === 'clear') {
    if (dialogFormData.value[filterField] !== '') {
      dialogFormData.value[filterField] = '';
      search_btn();
    }
  }

  //确定操作
  if (state === 'confirm') {
    dialogFormData.value[filterField] = selectedValue;
    if (selectedValue !== '') {
      search_btn();
    }
  }
}

//处理排产累计数量
const getSchedulingList = (list,total) => {
  const sortedData = [...list].sort((a, b) => new Date(a.planTime) - new Date(b.planTime));
  let cumulativeQuantity = Number(total);

  return sortedData.map(item => {
    if (item.quantity <= cumulativeQuantity){
      cumulativeQuantity -= item.quantity;
    } else {
      cumulativeQuantity = 0;
    }
    return { ...item, cumulativeQuantity };
  });
}

const dealTableWidth = () => {
  const col = unref(formattedDateColumns);
  if(col.length > 4){
    return '160';
  }
  return '';
}
</script>

<style lang="scss" scoped>
.quantity-input {
  margin-left: 10px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
}
:deep(.el-card__header){
  border:none;
  padding-bottom:0px;
}
:deep(.el-card__body){
  padding-top:0px;
}
</style>
